package com.trz.cqrs.core.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.trz.cqrs.core.entity.EventEntity;
import com.trz.cqrs.core.enums.EventState;
import com.trz.cqrs.core.mapper.EventEntityMapper;
import com.trz.cqrs.es.event.EventView;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class EventRepository extends ServiceImpl<EventEntityMapper, EventEntity> implements IService<EventEntity> {

    public Optional<EventEntity> findByIdAndEventStateNot(Long id, EventState succeeded) {
        EventEntity entity = new EventEntity();
        entity.setId(id);
        entity.setEventState(succeeded);
        QueryWrapper<EventEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        queryWrapper.ne("event_state",succeeded.name());
        return Optional.ofNullable(getOne(queryWrapper, true));
    }

    public EventEntity updateProcessAndGet(EventView view) {
        EventEntity entity = null;
        UpdateWrapper<EventEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", view.getId());
        updateWrapper.eq("event_state", EventState.CREATED);
        EventEntity update = new EventEntity();
        update.setEventState(EventState.PROCESSING);
        Boolean isSuccess = update(update, updateWrapper);
        if (isSuccess){
            entity = getById(view.getId());
        }
        return entity;
    }

    public List<EventEntity> selectList(List<EventState> stateList, Date date, String priority) {
        QueryWrapper<EventEntity> query = new QueryWrapper<>();
        query.in("event_state",stateList.stream().map(t->t.name()).collect(Collectors.toList()));
        query.eq("priority",priority);
        query.le("update_time",date);
        //只查id
        query.select("id");
        List<EventEntity> result =  baseMapper.selectList(query);
        return result;
    }
}
